package com.travel.commons.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * http请求获取工具
 *
 * @author pengrui.r@qq.com
 */
@Slf4j
public class HttpUtils {
    /**
     * 获取HttpServletRequest请求
     * @return httpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes requestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        if (requestAttributes != null) {
            return requestAttributes.getRequest();
        }
        return null;
    }

    /**
     * 获取请求的Origin
     * @return origin
     */
    public static String getOrigin() {
        HttpServletRequest request = getHttpServletRequest();
        if (request != null) {
            return request.getHeader("Origin");
        }
        return null;
    }

    /**
     * 获取请求的token
     * @return token
     */
    public static String getToken(HttpServletRequest httpRequest) {
        String token = httpRequest.getHeader("token");
        log.info("Get request's token : " + token);

        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter("token");
        }

        return token;
    }
}
